<template>
	<view class="record-detail page-content">
		<nav-bar back >{{ pageTitle }}</nav-bar>
		<view class="page-main page-main-content">
			<view class="example-body">
				<uni-datetime-picker :clear-icon="false" v-model="range" type="daterange" @change="changeDate"/>
			</view>
			<view class="tab-wrap">
				<view class="total middleCenter">
					{{totalTips}}
				</view>
				<view class="tab">
						<!-- <view class="tabs-item" v-for="item in tabs" @click="changeTab(item)">
							{{item.label}}
						</view> -->
						<view :class="{
							'tabs-item':true,
							active:item.key === active
						}" v-for="item in tabs" @click="changeTab(item)">
							{{item.label}}
						</view>
						<!-- <view class="tabs-item active">
							喂奶时长
						</view> -->
				</view>
			</view>
			<!-- :ontouch="true" -->
			<view class="charts-box">
			    <qiun-data-charts 
					  type="column"
					  :opts="opts"
					  :chartData="chartData"
					  :ontouch="true"
					  @getIndex="handleChartClick" 
				/>
			</view>
			<empty v-if="currentDayList.length <= 0" />
			<data-info :data="item" v-for="(item,index) in currentDayList"
			@handlderClick="goDetail(item.id)"></data-info>
			
		</view>
	</view>
</template>

<script setup>
	import {ref, reactive,computed} from 'vue'
	import { onLoad,onReachBottom } from '@dcloudio/uni-app';
	import {getDataByKey,getHistoryData} from '@/utils/index.js'
	import dayjs from 'dayjs'
	import isSameOrAfter from 'dayjs/plugin/isSameOrAfter';
	import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
	const chartsRef = ref(null)
	const tabs = ref([])
	const active = ref('')
	const clickIndex= ref('') 
	
	
	const handleChartClick = (e)=>{
		clickIndex.value = e.currentIndex.index
	}	
	
	const changeTab = (e)=>{
		if(e.key !== active.value){
			clickIndex.value = -1
			active.value = e.key
			renderChart()
		}
	}
	
	// 加载插件
	dayjs.extend(isSameOrAfter);
	dayjs.extend(isSameOrBefore);
	
	const chartData = ref({})
	let pageTitle = ref('') 
	const queryParams = ref({})
	const range = ref([])
	const xAxis = ref([])
	
	const dayList = ref([])
	
	const currentDayList = computed(()=>{
		if(!clickIndex.value) return []
		console.log(dayList.value[Number(clickIndex.value)] || [])
		let list = dayList.value[Number(clickIndex.value)] ? dayList.value[Number(clickIndex.value)].data : []
		return list
	})
	
	const totalTips = computed(()=>{
		let indexStr ='共计'
		let otherStr = ''
		
		let tabList = JSON.parse(JSON.stringify(tabs.value)).reverse()
		tabList.forEach(item=>{
			let { key,unit } = item
			if(queryParams.value.type === 'BodyTemperature' && key === 'actualMilkAmount'){
				indexStr= '最高体温'
				let aaa = dayList.value.reduce((prev,item)=>{
					let itemData = item.data.map(ii=>ii[key])
					return [...prev,...itemData]
				},[])
				console.log(aaa,'aaa66666666666666');
				otherStr += Math.max(...aaa);
			}else {
				otherStr += getAllData(key).reduce((prev,k)=>{
					let val = k ||  0
					return prev += val
				},0)
			}
			
			console.log(item,unit,'*****');
			otherStr += unit + '  '
		})
		// let s = indexStr ?  `(${indexStr})次` : ''
		return `${indexStr}: ${otherStr} `
	})
	
	const changeDate = (e)=>{
		console.log(e);
		setChartData()
	}
	const opts = reactive({
		color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
		padding: [15,15,0,5],
		touchMoveLimit: 24,
		enableScroll: true,
		legend: {
			show:false
		},
		xAxis: {
		  disableGrid: true,
		  scrollShow: true,
		  itemCount: 7
		},
		yAxis: {
		  data: [
			{
			  min: 0
			}
		  ]
		},
		extra: {
		  column: {
			type: "group",
			width: 10,
			activeBgColor: "#000000",
			activeBgOpacity: 0.08,
			seriesGap:10
		  }
		}
	})
	let res = reactive({
		categories: [],
		series: [
		  {
			data: []
		  }
		]
	});
	chartData.value = JSON.parse(JSON.stringify(res));
	
	const goDetail=(id)=>{
		uni.navigateTo({
			url: `/pages/tabbar/tabbar-1/recordInfo?id=${id}`
		});
	}
	
	const getAllData = (key)=>{
		if(key === 'index'){
			return dayList.value.map(item=>{
				return item.data.length
			})
		}
		
		if(queryParams.value.type === 'BodyTemperature' && key === 'actualMilkAmount'){
			return dayList.value.map(item=>{
				let itemData = item.data.map(ii=>ii[key])
				console.log(item,'item',itemData);
				return itemData.length>0 ? Math.max(...itemData) :'';
			})
		}
		
		return dayList.value.map(item=>{
			return item.data.reduce((prev,k)=>{
				let val = k[key] ? Number(k[key]) : 0
				return prev += val
			},0)
		})
	}
	
	
	
	const renderChart = ()=>{
		res.categories= xAxis.value
		let activeKey = active.value
		res.series[0].data = getAllData(activeKey)
		
		console.log(res.series[0].data);
		res.series[0].name= pageTitle.value
		chartData.value = JSON.parse(JSON.stringify(res));
	}
	
	
	const setChartData = ()=>{
		let [start,end] = range.value
		
		// 定义时间区间
		const startTime = dayjs(start); // 时间区间的起始时间
		const endTime = dayjs(end);   // 时间区间的结束时间
		
		// const startTime = dayjs('2025-04-10'); // 时间区间的起始时间
		// const endTime = dayjs(end);   // 时间区间的结束时间
		
		 const diffInMilliseconds = Math.abs(endTime.diff(startTime));
		let num = diffInMilliseconds / (1000 * 60 * 60 * 24);
		console.log(num,'天数');
		
		let xList = new Array(num).fill('*').map((item,index)=>{
			return startTime.add(index,'day').format('MM.DD')
		})
		xList.push('今天')
		
		xAxis.value = xList
		console.log(xList,'xList');
		let dataStore = uni.getStorageSync(queryParams.value.type)
		// let dataList = []
		// if(dataStore){
		// 	Object.keys(dataStore).forEach(key=>{
		// 		let targetTime = dayjs(key);
		// 		if(targetTime.isSameOrAfter(startTime) && targetTime.isSameOrBefore(endTime)){
		// 			let obj ={
		// 				x:key,
		// 				data:dataStore[key]
		// 			}
		// 			dataList.push(obj)
		// 		}
		// 	}) 
		// }
		
		dayList.value = new Array(num+1).fill('*').map((item,index)=>{
			let currentDay = startTime.add(index,'day').format('YYYY-MM-DD')
			let list = dataStore[currentDay]  || []
			let cuList = list.map(listItem=>{
				return getHistoryData().find(fItem=>{
					return listItem.id === fItem.id
				})
				
			}) 
			return {
				data:cuList,
				currentDay
			}
		})
		renderChart()
		// console.log(dataList,dayList,'dataList',queryParams.value.type);
		// let dataRes = {
		// 	categories:xList,
		// 	series: [
		// 	  {
		// 		name: "目标值",
		// 		data: [35,36,31,33,13,34]
		// 	  }
		// 	]
		// };
		// chartData.value = JSON.parse(JSON.stringify(dataRes));
		// 默认滚动到最右边
		// setTimeout(() => {
		//   const scrollWidth = chart.scrollWidth; // 获取滚动条总宽度
		//   chart.scrollLeft(scrollWidth); // 设置滚动条位置到最右边
		// }, 100);
		
	}
	


	onLoad((options) => {
	  console.log('页面加载时的参数:',options,options.type);
	  let {type} = options
	  queryParams.value = options; // 将参数赋值给响应式变量
	 let dataInfo = getDataByKey(queryParams.value.type)
	  pageTitle.value=dataInfo.name
	  tabs.value = dataInfo.tabs
	  active.value = dataInfo.tabs[0].key
	  // 获取当前时间
	  const now = dayjs();
	  
	  // 获取一个月前的时间
	  const oneMonthAgo = now.subtract(1, 'month').format('YYYY-MM-DD');
	  range.value = [oneMonthAgo,now.format('YYYY-MM-DD')]
	  setChartData()
	  
	 
	})
	
	
</script>

<style lang="scss" scoped>
	.page-main-content{
		padding: 20rpx;
	}
  .charts-box {
    width: 100%;
    height: 300rpx;
	margin-bottom: 20rpx;
  }
  .tab-wrap{
	  margin: 40rpx 0;
	  display: flex;
	  justify-content: space-between;
	  .total{
		  color: #999;
		  font-size: 24rpx;
	  }
	  .tab{
		  background: rgba(0,0,0, 0.03);
		  border-radius: 10rpx;
		  padding:6rpx ;
		  display: flex;
		  .tabs-item{
			  padding: 5rpx 20rpx;
			  color: rgba(0,0,0, 0.5);
			  font-size: 24rpx;
		  }
		  .active{
			  background: #fff;
			  color: #333;
			  border-radius: 12rpx;
		  }
	  }
  }
</style>